package org.kunlong.netix.listner.standardlistner;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.kunlong.netix.exception.LifeCycleException;
import org.kunlong.netix.listner.Listner;
import org.kunlong.netix.processor.Processor;

public class StandardListner implements Listner, Runnable {
	private Processor processor;
	private int port;
	private ServerSocket server;
	private boolean status = false;

	public StandardListner() {
		// TODO Auto-generated constructor stub
	}
	public void addProcessor(Processor p) {
		// TODO Auto-generated method stub
		processor=p;
	}
	public Processor getProcessor() {
		return processor;
	}

	public void setProcessor(Processor processor) {
		this.processor = processor;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

	public StandardListner(Processor p, int port) {
		// TODO Auto-generated constructor stub
		this.port = port;
		this.processor = p;
	}

	public void init() throws LifeCycleException {
		// TODO Auto-generated method stub
		try {
			System.out.println("Starting Listner......: Port:["+port+"]");
			server = new ServerSocket(port);
			status = true;
		} catch (IOException e) {
			// TODO: handle exception
			throw new LifeCycleException(e);
		}
	}

	public void start() throws LifeCycleException {
		// TODO Auto-generated method stub
		Thread t = new Thread(this);
		t.start();
	}

	public void stop() throws LifeCycleException {
		// TODO Auto-generated method stub
		status = false;
	}

	public void run() {
		// TODO Auto-generated method stub
		try {
			while (status) {
				Socket s = server.accept();
				processor.process(s);
			}
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

}
